var express = require('express');
var router = express.Router();
const ioredis = require('ioredis')
// 1. 建立连接
const redis = new ioredis({
    port: 6379,
    host: '139.155.233.245',
    showFriendlyErrorStack: true
})
/**
 * @description 打捞一个漂流瓶
 */
router.get("/", async (req, res, next) => {
    try {
        let {user, type} = req.query
        // 参数校验
        if (!user) {
            throw Error("用户名或id不能为空")
        }
        // 未传type
        if (!type || type === 'all') {
            const number = parseInt(Math.random() * 100)
            console.log(number)
            if (number % 2 === 0) {
                type = 'male'
            } else {
                type = 'female'
            }
        }
        let userInfo
        if (type === 'male') {
            // 获取随机id
            let ids = await redis.smembers("maleId")
            const index = parseInt(Math.random() * ids.length)
            let id = ids[index]
            userInfo = await redis.hgetall(`male:${id}`)
            console.log('userInfo', userInfo)
        } else {
            // 获取随机id
            let ids = await redis.smembers("femaleId")
            const index = parseInt(Math.random() * ids.length)
            let id = ids[index]
            userInfo = await redis.hgetall(`female:${id}`)
            console.log('userInfo', userInfo)
        }
        delete userInfo.id
        // delete userInfo.id
        res.json({
            "code": 1,
            "msg": userInfo
        })
    } catch (e) {
        // console.log(e)
        res.json({
            "code": 0,
            "msg": e.message
        })
    }
})

router.post('/', async (req, res, next) => {
    try {
        console.log(req.query)
        let {time, type, owner, content} = req.query
        if (!time) {
            time = Date.now()
        }
        console.log(type)
        if (type === 'male') {
            let id = (await redis.smembers('maleId')).length + 1
            console.log('id=====', id)
            await redis.multi()
                .sadd('maleId', id)
                .hset(`male:${id}`, {
                    id,
                    owner,
                    type,
                    time,
                    content
                })
                .exec()

        } else {
            let id = (await redis.smembers('femaleId')).length + 1
            console.log('id=====', id)
            await redis.multi()
                .sadd('femaleId', id)
                .hset(`female:${id}`, {
                    id,
                    owner,
                    type,
                    time,
                    content
                })
                .exec()
        }
        res.json({
            "code": 1,
            "msg": "成功扔出"
        })
    } catch (e) {
        res.json({
            "code": 0,
            "msg": e.message
        })
    }
})
module.exports = router;
